// Code Behind for index.mxml
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.setTimeout;
	
	import jcrweb.as3.FlexUtil;
	import jcrweb.as3.LanguageUtil;
	import jcrweb.as3.LoginUtil;
	import jcrweb.as3.RequestUtil;
	
	import mx.collections.XMLListCollection;
	import mx.containers.HBox;
	import mx.controls.Alert;
	import mx.controls.Image;
	import mx.controls.LinkButton;
	import mx.managers.PopUpManager;	
	
	[Bindable]
	private var rootDevice:XMLList;
	[Bindable]
	private var maindata:XMLListCollection;
	[Bindable]
	private var treeItemObj:XML;
	[Bindable]
    private var rTreeList:XMLListCollection;
	[Bindable]
	private var path:String;
	[Bindable]
	private var pathName:String;
	[Bindable]
	private var languageUtil:LanguageUtil;
	
	private var linkArray:Array = null;
	private var loadingTreeFlag:Boolean = false;
	[Bindable]
	private var loginUtil:LoginUtil;

	[Bindable]
	[Embed(source='../WebContent/images/attent.gif')]
	private var iconAlert:Class;
	[Bindable]
	[Embed(source='../WebContent/images/error.gif')]
	private var iconError:Class;
	[Bindable]
	[Embed(source='../WebContent/images/ok.gif')]
	private var iconOk:Class;

	private function loginChecked():void{
		setTimeout(loginCheck,10);
	}
	private function loginCheck():void{
		this.loginUtil = new LoginUtil();
		loginUtil.loginCheck();
		showLoginUser();
	}
	private function showLoginUser():void{
		loginLabel.text = "Login user :" + LoginUtil.getLoginUsername();
		if(LoginUtil.getLoginUsername() == "admin"){
			userBtn.enabled = true;
			userBtn.alpha = 1.0;
		}
	}
	// Event handler to initialize the MenuBar control.
	private function init():void {
		setTimeout(showLoginUser,10);
		//init tree
	   	rTreeList = new XMLListCollection();
	   	var treeInitStr:String = "<node id='0' label='/' path='/'>"
				+ "</node>";
		var treeInitXml:XML = new XML(treeInitStr);
		rTreeList.addItem(treeInitXml);	
	    //init maindata
	    maindata = new XMLListCollection();
		this.pathName = "";
		this.path="";
		tabNav.selectedIndex = 0;
		requestLink();
		
		languageUtil = LanguageUtil.getInstance();
	}
	private function requestLink():void{
		if(!LoginUtil.isLogin()){
			return;
		}
		var para:String = new String();
		para +="&userCode="+LoginUtil.getLoginUsercode();
		para =  encodeURI(para);
		para =  encodeURI(para);
		
		var url:String = RequestUtil.LOADLINK_URL+para;
		RequestUtil.sendRequest(url,Event.COMPLETE,loadLink);
	}
	            
	private function loadLink(event:Event):void{
		linkArray = new Array();
		linkTab.removeAllChildren();
		var loader:URLLoader = URLLoader(event.target); 
		var resutlSize:String = FlexUtil.getTag(loader.data,FlexUtil.RESULT_SIZE);
		var allData:String = FlexUtil.getTag(loader.data,FlexUtil.RESULT_DATA)
		if(resutlSize != "0"){
			for(var j:int=0;j<Number(resutlSize);j++){
				var newnode:XML = new XML(FlexUtil.getTag(allData,new String(j+1)));
				var linkBtn:LinkButton = new LinkButton();
				var linkImage:Image = new Image();
				linkImage.source = "images/del.png";
				linkImage.useHandCursor = true;
				var hbox:HBox = new HBox();
				hbox.styleName = "hbox1";
				linkBtn.label = newnode.name;
				linkBtn.addEventListener(MouseEvent.CLICK,gotoLink);
				linkImage.buttonMode = true;
				linkImage.toolTip = "delete link: "+newnode.name;
				linkImage.name = newnode.name;
				linkImage.addEventListener(MouseEvent.CLICK,delLink);
				hbox.addChild(linkBtn);
				hbox.addChild(linkImage);
				linkTab.addChild(hbox);
				linkArray.push(newnode);
			}
		}
	}
	private function gotoLink(event:Event):void{
		var linkBtn:LinkButton = LinkButton(event.target);
		for(var i:int;i<this.linkArray.length;i++){
			var nodeXml:XML = linkArray[i] as XML;
			if(nodeXml.name == linkBtn.label){
				this.path = nodeXml.linkpath;
				requestMainData(nodeXml.linkpath);
				break;
			}
		}
	}
	private function delLink(event:Event):void{
		var linkImage:Image = event.currentTarget as Image;
		var strId:String = null;
		for(var i:int;i<this.linkArray.length;i++){
			var nodeXml:XML = linkArray[i] as XML;
			if(nodeXml.name == linkImage.name){
				strId = nodeXml.id
			}
		}
		if(strId == null){
			return;
		}
		var para:String = new String();
		para +="&id="+strId;
		para =  encodeURI(para);
		para =  encodeURI(para);
		var url:String = RequestUtil.DELETELINK_URL+para;
		RequestUtil.sendRequest(url,Event.COMPLETE,deleteLinkComplete);
	}
	public function deleteLinkComplete(event:Event):void {
		var loader:URLLoader = URLLoader(event.target); 
		var isError:String = FlexUtil.getTag(loader.data,FlexUtil.IS_ERROR);
		if(isError == "true" ){
			var errorMes:String = FlexUtil.getTag(loader.data,FlexUtil.ERROR_MES_TAG);
			Alert.show("Faild!"+errorMes,"Error",0,null,null,iconError);
		}
		requestLink();
	}
	private function createTreeEventNotify(event:Event): void{
		if(loadingTreeFlag){
			return;
		}
		loadingTreeFlag = true;
		treeItemObj = Tree(event.target).selectedItem as XML;
		this.path = treeItemObj.@path;
		//load main data
		requestMainData(treeItemObj.@path);
		//request tree data
		requestTreeData(this.path);
	}
	private function createLoadDataNotify(event:Event):void{
		var maindataXml:XML = DataGrid(event.target).selectedItem as XML;
		if(maindataXml.isfile == "true"){
			var myPanel1:propertycdialog = propertycdialog(PopUpManager.createPopUp(this, propertycdialog, true));
			myPanel1.setId(maindataXml.id);
			myPanel1.setPath(this.path);
			myPanel1.setPathName(this.pathName);
			myPanel1.setName(maindataXml.name);
			myPanel1.setCreaterCode(maindataXml.createrCode);
			myPanel1.setCreaterName(maindataXml.createrName);
			myPanel1.setDatetime(maindataXml.datetime);
			myPanel1.setNote(maindataXml.note);
			myPanel1.setFiles(maindataXml.file1Id,maindataXml.file1Name,1);
			myPanel1.setFiles(maindataXml.file2Id,maindataXml.file2Name,2);
			myPanel1.setFiles(maindataXml.file3Id,maindataXml.file3Name,3);
			myPanel1.setFiles(maindataXml.file4Id,maindataXml.file4Name,4);
			myPanel1.setFiles(maindataXml.file5Id,maindataXml.file5Name,5);
			myPanel1.setFiles(maindataXml.file6Id,maindataXml.file6Name,6);
			myPanel1.setFiles(maindataXml.file7Id,maindataXml.file7Name,7);
			myPanel1.setFiles(maindataXml.file8Id,maindataXml.file8Name,8);
			myPanel1.setFiles(maindataXml.file9Id,maindataXml.file9Name,9);
			myPanel1.setFiles(maindataXml.file10Id,maindataXml.file10Name,10);
			//myPanel1.getAllVersion();
			PopUpManager.centerPopUp(myPanel1);
			requestMainData(this.path);
		}else{
		    this.path = maindataXml.path
		    if(tree1!=null && treeItemObj !=null){
		    	for each(var treeXml:XML in treeItemObj.children()){
	        		if(treeXml.@path == this.path){
	        			treeItemObj = treeXml;
	        			requestTreeData(treeItemObj.@path);
	        			break;
	        		}
	        	}
		     }
			//load main data
			requestMainData(this.path);
		}
	}
	private function requestTreeData(path:String):void{
		var para:String = new String();
		para +="?path="+path;
		para =  encodeURI(para);
		para =  encodeURI(para);
		var url:String = RequestUtil.LOADTREE_URL+para;
		RequestUtil.sendRequest(url,Event.COMPLETE,loadTreeData);
	}
	private function loadTreeData(event:Event):void { 
		var loader:URLLoader = URLLoader(event.target); 
		var resutlSize:String = FlexUtil.getTag(loader.data,FlexUtil.RESULT_SIZE);
		if(resutlSize != "0"){
			delete treeItemObj.*;

			var allData:String = FlexUtil.getTag(loader.data,FlexUtil.RESULT_DATA)
			for(var j:int=0;j<Number(resutlSize);j++){
				var newnode:XML = new XML(FlexUtil.getTag(allData,new String(j+1)));
				treeItemObj.appendChild(newnode);
			}
			rTreeList.itemUpdated(treeItemObj.*);
			tree1.expandChildrenOf(treeItemObj,true);
		}
		//rTreeList.g.itemUpdated(treeItemObj);
		loadingTreeFlag = false;
	}
	
	private function requestMainData(path:String):void{
		var para:String = new String();
		para +="&path="+path;
		para =  encodeURI(para);
		para =  encodeURI(para);
		var url:String = RequestUtil.LOADDATA_URL+para;
		RequestUtil.sendRequest(url,Event.COMPLETE,loadMainData);	
	}
	private function loadMainData(event:Event):void{
		maindata = new XMLListCollection();
		var loader:URLLoader = URLLoader(event.target); 
		var resutlSize:String = FlexUtil.getTag(loader.data,FlexUtil.RESULT_SIZE);
		var allData:String = FlexUtil.getTag(loader.data,FlexUtil.RESULT_DATA)
		if(resutlSize != "0"){
			for(var j:int=0;j<Number(resutlSize);j++){
				var newnode:XML = new XML(FlexUtil.getTag(allData,new String(j+1)));
				maindata.addItem(newnode);
			}
		}
		this.pathName = FlexUtil.getTag(allData,"pathname");
		if(this.pathName == ""){
			this.pathName = "/";
		}
	}		
	private function showCreatedirdialog():void{
		var myPanel:createdirdialog = createdirdialog(PopUpManager.createPopUp(this, createdirdialog, true));		
		myPanel.setCreaterCode(LoginUtil.getLoginUsercode());
		myPanel.setCreaterName(LoginUtil.getLoginUsername());
		if(dataGrid.selectedItem != null){
			var nodeXml:XML = dataGrid.selectedItem as XML;
			if(nodeXml.isfile == "true"){
			 	myPanel.setPath(this.path);
			 	myPanel.setPathName(this.pathName);
			 	myPanel.addEventListener(Event.REMOVED_FROM_STAGE,reFresh);
				PopUpManager.centerPopUp(myPanel);
			}else{
			 	myPanel.setPath(this.path+"/"+nodeXml.id);
			 	if(this.pathName == "/"){
			 		myPanel.setPathName(this.pathName+nodeXml.name);
			 	}else{
			 		myPanel.setPathName(this.pathName+"/"+nodeXml.name);
			 	}
			 	myPanel.addEventListener(Event.REMOVED_FROM_STAGE,reFresh);
				PopUpManager.centerPopUp(myPanel);
			}
		}else if(tree1 != null && tree1.selectedItem != null){
			myPanel.setPath(this.path);
			myPanel.setPathName(this.pathName);
			myPanel.addEventListener(Event.REMOVED_FROM_STAGE,reFresh);
			PopUpManager.centerPopUp(myPanel);
		}else{
			Alert.show("Sorry,choose a path first please!","Attention",0,null,null,iconAlert);
			PopUpManager.removePopUp(myPanel);
		}
	}
	private function showCreateContent():void{	
		var myPanel:createcondialog = createcondialog(PopUpManager.createPopUp(this, createcondialog, true));
		myPanel.setCreaterCode(LoginUtil.getLoginUsercode());
		myPanel.setCreaterName(LoginUtil.getLoginUsername());
		if(dataGrid.selectedItem != null){
			var nodeXml:XML = dataGrid.selectedItem as XML;
			if(nodeXml.isfile == "true"){
			 	myPanel.setPath(this.path);
			 	myPanel.setPathName(this.pathName);
			 	myPanel.addEventListener(Event.REMOVED_FROM_STAGE,reFresh);
				PopUpManager.centerPopUp(myPanel);
			}else{
			 	myPanel.setPath(this.path+"/"+nodeXml.id);
			 	if(this.pathName == "/"){
			 		myPanel.setPathName(this.pathName+nodeXml.name);
			 	}else{
			 		myPanel.setPathName(this.pathName+"/"+nodeXml.name);
			 	}
			 	myPanel.addEventListener(Event.REMOVED_FROM_STAGE,reFreshCon);
			 	PopUpManager.centerPopUp(myPanel);
			}
		}
		else if(pathName == "/"){
			Alert.show("Sorry,create a content in this path is not leave!","Attention",0,null,null,iconAlert);
			PopUpManager.removePopUp(myPanel);
		}
		else if(tree1!=null && tree1.selectedItem != null && pathName != ""){
		 	myPanel.setPath(this.path);
		 	myPanel.setPathName(this.pathName);
		 	myPanel.addEventListener(Event.REMOVED_FROM_STAGE,reFreshCon);
		 	PopUpManager.centerPopUp(myPanel);
		}
		else{
			Alert.show("Sorry,choose a path first please!","Attention",0,null,null,iconAlert);
			PopUpManager.removePopUp(myPanel);
		}
	}
	private function showPropertyddialog():void{
		if(dataGrid.selectedItem!=null){
			var nodeXml:XML = dataGrid.selectedItem as XML;
			if(nodeXml.isfile == "true"){
				var myPanel1:propertycdialog = propertycdialog(PopUpManager.createPopUp(this, propertycdialog, true));
				myPanel1.setId(nodeXml.id);
			 	myPanel1.setPath(nodeXml.path);
			 	myPanel1.setPathName(this.pathName);
			 	myPanel1.setName(nodeXml.name);
			 	myPanel1.setCreaterCode(nodeXml.createrCode);
			 	myPanel1.setCreaterName(nodeXml.createrName);
			 	myPanel1.setDatetime(nodeXml.datetime);
			 	myPanel1.setNote(nodeXml.note);
			 	myPanel1.setFiles(nodeXml.file1Id,nodeXml.file1Name,1);
			 	myPanel1.setFiles(nodeXml.file2Id,nodeXml.file2Name,2);
			 	myPanel1.setFiles(nodeXml.file3Id,nodeXml.file3Name,3);
			 	myPanel1.setFiles(nodeXml.file4Id,nodeXml.file4Name,4);
			 	myPanel1.setFiles(nodeXml.file5Id,nodeXml.file5Name,5);
			 	myPanel1.setFiles(nodeXml.file6Id,nodeXml.file6Name,6);
			 	myPanel1.setFiles(nodeXml.file7Id,nodeXml.file7Name,7);
			 	myPanel1.setFiles(nodeXml.file8Id,nodeXml.file8Name,8);
			 	myPanel1.setFiles(nodeXml.file9Id,nodeXml.file9Name,9);
			 	myPanel1.setFiles(nodeXml.file10Id,nodeXml.file10Name,10);
			 	//myPanel1.getAllVersion();
			 	myPanel1.addEventListener(Event.REMOVED_FROM_STAGE,reFreshCon);
			 	PopUpManager.centerPopUp(myPanel1); 
			}else{
				var myPanel2:propertyddialog = propertyddialog(PopUpManager.createPopUp(this, propertyddialog, true));
				myPanel2.setId(nodeXml.id);
			 	myPanel2.setPath(this.path);
			 	myPanel2.setPathName(this.pathName);
			 	myPanel2.setName(nodeXml.name);
			 	myPanel2.setCreaterCode(nodeXml.createrCode);
			 	myPanel2.setCreaterName(nodeXml.createrName);
			 	myPanel2.setDatetime(nodeXml.datetime);
			 	myPanel2.setNote(nodeXml.note);
			 	myPanel2.addEventListener(Event.REMOVED_FROM_STAGE,reFresh);
			 	PopUpManager.centerPopUp(myPanel2); 
			}
		}
	}

	private var showmessageType:int = 0;
	
	private function UpEventNotify():void{
		if(this.path == null || this.path == "" || this.path == "/"){
			return;
		}
	    this.path = FlexUtil.getUpPath(this.path);
		//load main data
		requestMainData(this.path);
	}
	private function showCreateLink():void{		
		if(dataGrid.selectedItem != null){
			var nodeXml:XML = dataGrid.selectedItem as XML;
			if(nodeXml.isfile == "true"){
				Alert.show("Sorry,this is a content\n"+"Choose a directory please!","Attention",0,null,null,iconAlert);
				return;
			}
			var linkName2:String = nodeXml.name;
			if(nodeXml.isfile == true){
				var linkName:String = "Content";
			}
			else{
				linkName = "Directory";
			}
			linkAlert.visible = true;
			linkText.text="Do you want to create a link for \n["+linkName+": "+ linkName2 +"]";
		}else if(tree1 != null && tree1.selectedItem != null && (pathName != "" && pathName != "/")){
			linkAlert.visible = true;
			var treeXml:XML = tree1.selectedItem as XML;
			var linkName1:String = this.pathName.substring(this.pathName.lastIndexOf("/")+1);
			linkText.text="Do you want to create a link for \n[Directory: "+ linkName1 +"]";
		}

	}
	private function createLink():void{
		var nodeXml:XML;
		var para:String = new String();
		if(dataGrid.selectedItem!=null){
			nodeXml = dataGrid.selectedItem as XML;
			para +="&linkpath="+nodeXml.path;
			para +="&createrCode="+LoginUtil.getLoginUsercode();
			para +="&name="+nodeXml.name;
		}else if(tree1 != null && tree1.selectedItem != null && (pathName != "" && pathName != "/")){
			nodeXml = tree1.selectedItem as XML;
			para +="&linkpath="+nodeXml.@path;
			para +="&createrCode="+LoginUtil.getLoginUsercode();
			para +="&name="+nodeXml.@label;
		}else{
			Alert.show("Sorry,Choose a directory please!","Attention",0,null,null,iconAlert);
			linkAlert.visible = false;
		}
		para =  encodeURI(para);
		para =  encodeURI(para);
		
		var url:String = RequestUtil.CREATELINK_URL+para;
		RequestUtil.sendRequest(url,Event.COMPLETE,createLinkfinish);	
	}
	private function createLinkfinish(event:Event):void {
		var loader:URLLoader = URLLoader(event.target); 
		var isError:String = FlexUtil.getTag(loader.data,FlexUtil.IS_ERROR);
		if(isError == "true" ){
			var errorMes:String = FlexUtil.getTag(loader.data,FlexUtil.ERROR_MES_TAG);
			Alert.show("Faild ! "+errorMes,"Error",0,null,null,iconError);
		}
		linkAlert.visible = false;
		Alert.show("Create link successful!","Successful",0,null,null,iconOk);
		requestLink();
	}
	private function reFresh(event:Event=null):void{
		requestMainData(this.path);
		requestLink();
		if(tree1!=null && treeItemObj !=null && treeItemObj.@path == this.path){
			requestTreeData(this.path);
		}
	}
	private function reFreshCon(event:Event=null):void{
		requestMainData(this.path);
	}
	private function showUserManage():void{
		var myPanel:usermanager = usermanager(PopUpManager.createPopUp(this, usermanager, true));
		 PopUpManager.centerPopUp(myPanel);
	}
	private function logout():void{
		this.loginUtil.logout();
	}
	private function nameSearch():void{	
		if(searchNameTxt.text == ""){
			Alert.show("Input a name first please!","Attention",0,null,null,iconAlert);
		}
		else{
			var para:String = new String();
			para +="&name="+searchNameTxt.text;
			para =  encodeURI(para);
			para =  encodeURI(para);
			var url:String = RequestUtil.SEARCH_URL+"?type=name"+para;
			RequestUtil.sendRequest(url,Event.COMPLETE,loadSearchData);
		}
	}
	private function idSearch():void{	
		searchTxt.restrict = "0-9";
		var searchCon:int = int(searchTxt.text);
		if(searchCon == 0){
			Alert.show("Input a id first please!","Attention",0,null,null,iconAlert);
		}
		else{
			var para:String = new String();
			para +="&id="+searchCon;
			para =  encodeURI(para);
			para =  encodeURI(para);
			var url:String = RequestUtil.SEARCH_URL+"?type=id"+para;
			RequestUtil.sendRequest(url,Event.COMPLETE,loadSearchData);
		}
	}
	private function loadSearchData(event:Event):void{
		maindata = new XMLListCollection();
		var loader:URLLoader = URLLoader(event.target); 
		var resutlSize:String = FlexUtil.getTag(loader.data,FlexUtil.RESULT_SIZE);
		var allData:String = FlexUtil.getTag(loader.data,FlexUtil.RESULT_DATA)
		if(resutlSize != "0"){
			for(var j:int=0;j<Number(resutlSize);j++){
				var newnode:XML = new XML(FlexUtil.getTag(allData,new String(j+1)));
				maindata.addItem(newnode);
			}
			this.pathName = FlexUtil.getTag(allData,"parentPathname");
			if(this.pathName == ""){
					this.pathName = "/";
			}
			this.path = FlexUtil.getTag(allData,"parentPath");
		}
		
	}
